const { ipcMain, BrowserWindow } = require("electron");
const { default: WinState } = require("electron-win-state");
const path = require('path')
const saveas = require('./saveas')

// css样式表不能折行
const cssText  =
`width:80px;\
height:60px;\
background-color:red;\
border-radius:5px;\
text-align:center;\
line-height:30px;\
position:fixed;\
bottom:50px;\
right:20px;\
z-index:1000;\
color:white;\
cursor:default`

// myApi在preload/window.js预加载文件中
const js = `
    const btn = document.createElement('button')
    btn.id = 'readit-button'
    btn.innerHTML='关闭窗口'
    btn.style.cssText = '${cssText}'
    btn.addEventListener('click',()=>{myApi.closeWindow()})
    document.body.appendChild(btn)
`;

let win = null;

ipcMain.handle("on-open-window-event", (e, url) => {
  const winState = new WinState({
    defaultHeight: 800,
    defaultWidth: 1200,
    // 防止窗口共享状态
    electronStoreOptions:{
        name:'window-state-open'
    }
  });
  win = new BrowserWindow({
    ...winState.winOptions,
    show: false,
    webPreferences:{
        preload:path.join(__dirname,'../preload/window.js')
    }
  });
  win.on("ready-to-show", () => {
    win.show();
  });
  win.loadURL(url);
  winState.manage(win);

  // 配置CSP规则
  const session = win.webContents.session;
  session.webRequest.onHeadersReceived((details, cb) => {
    cb({
      responseHeaders: {
        ...details.responseHeaders,
        "Content-Security-Policy": [
          "default-src * 'unsafe-inline'; \
          img-src * data:;\
          style-src * 'unsafe-inline';\
          font-src *;\
          script-src * 'unsafe-inline' 'unsafe-eval'",
        ],
      },
    });
  });

  win.webContents.executeJavaScript(js).catch(()=>{})
  win.webContents.on('context-menu',(e,args)=>{
    saveas(args.srcURL)
  })
});

ipcMain.handle('on-close-window-event',(e)=>{
    win.close()
})
